<template>
	<view class="cz_box">
		<view class="cz_button_list">
			<button @click="InitPrint">初始化打印机</button>
			<button @click="GetPrintList">获取Usb设备列表</button>
			<button @click="Bind">开始链接设备</button>
			<input v-model="PrintValue" type="text" />
			<button @click="PrintText">开始打印</button>
			<button @click="Close">断开Usb</button>
		</view>
		<view class="cz_Print">
			<view class="cz_Print_text">
				{{TipText}}
			</view>
			<view class="cz_Print_status">
				<view>打印机纸张状态：{{PaperStatus}}</view>
				<view>打印机打印状态：{{PrintStatus}}</view>
			</view>
		</view>
		<view class="cz_PrintList">
			<view @click="SelectPrint(item)" v-for="(item,index) in PrintList" :key="index" class="cz_PrintItem">
				{{item}}
			</view>
		</view>
	</view>
</template>

<script>
const Print = uni.requireNativePlugin("Print-Socket");
export default {
	data() {
		return {
			ButtonList:[],
			PrintList:[],
			PrintItem:{},
			TipText:'请开始',	//提示内容
			PaperStatus:'',
			PrintStatus:'未打印',
			PrintValue:'',
			BindPrint:{},
			// --------------------- 轮询读取设备状态 ------------------
			GetPrintStatusTimeID:''
		};
	},
	onReady() {
	},
	onHide() {
		this.CloseGetPrintStatus()
	},
	methods:{
		// 初始化打印机
		InitPrint(){
			Print.InitPrint((e)=>{
				this.TipText = e.data
			})
		},
		// 获取Usb设备列表
		GetPrintList(){
			Print.GetList((e)=>{
				this.TipText = JSON.stringify(e)
				this.PrintList = e
			})
		},
		// 开始连接设备
		Bind(){
			if(this.GetPrintStatusTimeID){
				clearInterval(this.GetPrintStatusTimeID)
			}
			if(!this.PrintItem){
				return uni.showToast({
					title:'请先选择设备',
					icon:'none'
				})
			}
			Print.Bind(this.PrintItem,(e)=>{
				this.TipText = e.data
				// 链接设备后开始轮询读取设备状态
				this.GetPrintStatusTimeID = setInterval(()=>{
					this.GetPrintStatus()
				},200)
			})
		},
		// 开始打印(文本)
		PrintText(){
			if(!this.PrintValue){
				return uni.showToast({
					title:'请先输入文本',
					icon:'none'
				})
			}
			Print.PrintText(this.PrintValue,5,5,20,20,(e)=>{
				this.TipText = e.data
			})
		},
		// 关闭设备
		Close(){
			Print.Close((e)=>{
				this.TipText = e.data
			})
		},
		// 轮询获取打印机的状态
		GetPrintStatus(){
			Print.GetPrintStatus((e)=>{
				this.PaperStatus = e.data.isPage
				this.PrintStatus = e.data.PrintStatus
			})
		},
		CloseGetPrintStatus(){
			clearInterval(this.GetPrintStatusTimeID)
		},
		SelectPrint(item){
			this.PrintItem = item
		}
	}
}
</script>

<style lang="scss">
.cz_box{
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	.cz_button_list{
		flex: 1;
	}
	.cz_Print{
		flex: 1;
		background-color: #000;
		color: #fff;
	}
	.cz_PrintList{
		flex:1;
		width: 300rpx;
	}
}
</style>
